import Countly from 'countly-sdk-web';
import { Code } from './Response';

class CLog {
	isInit: boolean;
	sessionId: string;
	constructor() {
		this.isInit = false;
		this.sessionId = '';
	}

	/**
	 * 初始化
	 * @param appkey - app key
	 */
	init(appkey: string, host: string) {
		if (!appkey || !host || this.isInit) return;

		this.isInit = true;

		Countly.debug = true;
		Countly.app_key = appkey;
		Countly.url = host; // 'https://countly.cosee.cc';
		// Countly.offline_mode = true;

		Countly.init();

		// automatically capture and report JavaScript errors
		Countly.q.push(['track_errors']);
	}

	/**
	 * 设置 session id
	 * @param sessionId - session id
	 */
	setSessionId(sessionId: string) {
		this.sessionId = sessionId;
	}

	/**
	 * report error to Countly
	 * @param {number} code - the name of the event (mandatory) api-error| ivcs-error
	 * @param {*} response - an object with key/value pairs to report with the event as segments
	 */
	// clog.error(code, response);
	error(code: number, response: any) {
		if (!this.isInit || !code || !response || code < Code.LOGIN_ERROR) return;
		if ([Code.CHECKED_CALL_PROGRESS_SESSION_ERROR].includes(code)) return;

		const key = code >= Code.READY_ERROR_AMS_EXCEPTION ? 'api-error' : 'ivcs-error';
		const ex = {};
		ex[key] = response;
		ex['code'] = code;
		if (this.sessionId) {
			ex['sessionId'] = this.sessionId;
		}
		Countly.log_error(JSON.stringify(ex));
	}

	/**
	 * report log to Countly
	 * @param {string} key - the name of the event (mandatory)
	 * @param {*} log - an object with key/value pairs to report with the event as segments
	 */
	log(key: string, log: any) {
		if (!this.isInit || !key || !log) return;
		const ex = {};
		ex['log'] = log;
		if (this.sessionId) {
			ex['sessionId'] = this.sessionId;
		}
		Countly.add_event({
			key: key,
			segmentation: JSON.stringify(ex)
		});
	}

	/**
	 * destroy Countly
	 */
	destroy() {
		this.isInit = false;
	}
}

const clog = new CLog();
export default clog;
